<template>
  <div class="homework-submit">
    <h2>提交作业：{{ homework.title }}</h2>
    <form @submit.prevent="submitHomework">
      <div class="form-group">
        <label>作业类型</label>
        <select v-model="submissionType" required>
          <option value="FILE">文件上传</option>
          <option value="TEXT">文本提交</option>
        </select>
      </div>

      <div v-if="submissionType === 'FILE'" class="form-group">
        <label>上传文件</label>
        <input type="file" @change="handleFileUpload" required>
      </div>

      <div v-if="submissionType === 'TEXT'" class="form-group">
        <label>作业内容</label>
        <textarea v-model="submissionText" required></textarea>
      </div>

      <button type="submit" :disabled="loading">
        {{ loading ? '提交中...' : '提交作业' }}
      </button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { homeworkService } from '@/services/homework.service'
import { useRouter } from 'vue-router'

const props = defineProps({
  homework: {
    type: Object,
    required: true
  }
})

const router = useRouter()
const submissionType = ref('FILE')
const submissionFile = ref<File | null>(null)
const submissionText = ref('')
const loading = ref(false)

const handleFileUpload = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files) {
    submissionFile.value = input.files[0]
  }
}

const submitHomework = async () => {
  try {
    loading.value = true
    const formData = new FormData()
    
    if (submissionType.value === 'FILE' && submissionFile.value) {
      formData.append('file', submissionFile.value)
    } else if (submissionType.value === 'TEXT') {
      formData.append('text', submissionText.value)
    }

    await homeworkService.submitHomework(props.homework.id, formData)
    router.push(`/courses/${props.homework.courseId}/homeworks`)
  } catch (error) {
    console.error('作业提交失败', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.homework-submit {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input, select, textarea {
  width: 100%;
  padding: 8px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
}
</style>